Reduce allocations in SourceGeneratedDocumentIdentity.Generate#80292
Conversation
1) The ArrayBuilder that was being used commonly ends up exceeding the re-use size threshold, thus negating it's pooling benefit 2) The ArrayBuilder.ToArray call can be replaced by an upfront array allocation as the size of the array is easy to determine 3) The Encoding.GetBytes calls can be changed to a non-allocating version 4) In NET, can avoid creating the SHA256 object 5) In NET, can use the HashData call to avoid allocating a return array 6) In NET, can create a guid without needing to create a new array
There was a problem hiding this comment.
Is there no streaming version that can avoid this alloc in the first place?
There was a problem hiding this comment.
Not that I could find (at least on the Encoding class)
There was a problem hiding this comment.
What about IncrementalHash.Create(Sha256), and then just append the data, instead of needing the initial array to copy into?
There was a problem hiding this comment.
we also have the Checksum type. Which, TBH, feels pretty appropriate for this use case :)
There was a problem hiding this comment.
OK, reworked with using Checksums instead. It does seem easier this way.
| Array.Resize(ref hash, 16); | ||
| var guid = new Guid(hash); | ||
| #if NET | ||
| Span<byte> bytesToChecksum = stackalloc byte[16]; |
There was a problem hiding this comment.
Do we have a constant we can use for this?
There was a problem hiding this comment.
I don't think there is anything in the Guid class accessible to us. A regexp search for "guid.*16" in Roslyn has several hits, but nothing is sticking out as a good candidate to use.
Found this while looking at a profile for the razor speedometer test. This isn't a huge allocator, but it's a couple MB of allocations that should be mostly removed.